﻿<?php
require_once "db.class.php";
require_once "config.php";
require_once './lib/SnsSigCheck.php';

//检查sig
$sig = $_GET['sig'];

unset($_GET['sig']);
		
$secret = $appkey.'&';
$method = 'GET';
$script_name = '/pay_for_qpoint/index.php';
$mysig = SnsSigCheck::makeSig( $method, $script_name, $_GET, $secret);
if ($sig != $mysig)
{
	$res = array('ret'=>4,'msg'=>'invalid sig');
}
else
{
	$params = array("host"=>"$host", "user"=>"$user", "pass"=>"$pass", "db"=>"$db");
	$db = new Dbclass($params, false);

	//解析参数
	$openid = $_GET['openid'];
	$ts = $_GET['ts'];
	$payitem = $_GET['payitem'];
	$token = $_GET['token'];
	
	$payitemStr = split('\*',$payitem);
	$objectIndex = $payitemStr[0];
	$objectNum = $payitemStr[2];
	
/*	//更新订单token
	$sql = "update ".$tb_order_profile." set delivered = true, payitem = '".$payitem."', amt = ".$amt." where token = '".$token."' and delivered = false";
	$result = $db->query($sql);
	//token不存在
	if ($db->affectedRows() <= 0)
	{
		$res = array('ret'=>3,'msg'=>'token not exist');
	}
	else
	{
 */		$sql = "select id from ".$tb_user_profile." where openId = '".$openid."'";
		$result = $db->query($sql);
		//用户已经存在
		if ($arr = $db->fetchArray($result))
		{
			$userId = $arr['id'];
			//发货
			$basicLevel = 0;
			//坦克
			if ($objectIndex > 9999 && $objectIndex < 20000)
			{
				$sql = "insert into ".$tb_tank_profile." (ownerId, tankIndex, basicLevel, strengthenLevel) values (".$userId.", ".$objectIndex.", ".$basicLevel.", 0)";
				for ($i = 0; $i < $objectNum - 1; $i++)
				{
					$sql .= ", (".$userId.",".$objectIndex.", ".$basicLevel.", 0)";
				}
				$result = $db->query($sql);
				if ($db->affectedRows() <= 0)
				{
					$res = array('ret'=>1,'msg'=>'fail to add tank');
				}
				else
				{
					//返回处理成功信息
					$res = array('ret'=>0,'msg'=>'OK');
				}
			}
			//装备、物品
			else
			{
				$sql = "update ".$tb_object_profile." set objectNum = objectNum + ".$objectNum." where ownerId = ".$userId." and objectIndex = ".$objectIndex." and basicLevel = ".$basicLevel." and strengthenLevel = 0 and tankId = 0";
				$db->query($sql);
				if ($db->affectedRows() <= 0)
				{
					$sql = "insert into ".$tb_object_profile." (ownerId, objectIndex, objectNum, basicLevel, strengthenLevel) values (".$userId.", ".$objectIndex.", ".$objectNum.", ".$basicLevel.", 0)";
					$db->query($sql);
				}
				if ($db->affectedRows() <= 0)
				{
					$res = array('ret'=>1,'msg'=>'fail to add object');
				}
				else
				{
					//返回处理成功信息
					$res = array('ret'=>0,'msg'=>'OK');
				}
			}
		}
		else
		{
			$res = array('ret'=>1,'msg'=>'user not exist');
		}
//	}
	$db->close();

}

echo json_encode($res);

?>
